import { _decorator, Collider2D, Component, Contact2DType, EventTouch, find, IPhysics2DContact, Node, tween, UIOpacity } from 'cc';
import { Constant } from '../AshFramework/Datas/Constant';
import { MapController } from './MapController';
import { GameManager } from './GameManager';
import { AudioManager, Audios } from '../AshFramework/Managers/AudioManager';
import { TipsController } from './TipsController';
const { ccclass, property } = _decorator;

@ccclass('Door')
export class Door extends Component {
    @property
    IsPass: boolean = false;

    @property
    IsLast: boolean = false;

    @property({ displayName: "新手提示" })
    IsTips: boolean = false;

    Collider2D: Collider2D = null;
    UIOpacity: UIOpacity = null;
    Door: Node = null;
    Tips: Node = null;

    IsOpen: boolean = false;

    protected onLoad(): void {
        this.Collider2D = this.getComponent(Collider2D);
        this.UIOpacity = this.getComponent(UIOpacity);
        this.Door = find("开门", this.node);
        this.Tips = find("Tips", this.node);

        if (this.Collider2D) {
            this.Collider2D.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this.Collider2D.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }

    Open(event: EventTouch) {
        if (this.IsOpen) return;
        //新手关卡
        if (this.IsTips && TipsController.Instance.IsPack) {
            this.Tips.active = true;
            this.Door.active = false;
            return;
        }
        if (!MapController.Instance.IsFinish || (!MapController.Instance.IsFinishAll && this.IsLast)) {
            this.Tips.active = true;
            this.Door.active = false;
            return;
        }
        AudioManager.PlaySound(Audios.OpenDoor);
        this.IsOpen = true;

        tween(this.UIOpacity)
            .to(1, { opacity: 0 }, { easing: `sineOut` })
            .call(() => {
                if (this.IsPass) {
                    //通关
                    GameManager.Instance.nextMap();
                }
                this.node.destroy();
            })
            .start();
    }


    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (otherCollider.group == Constant.Group.PLAYER) {
            this.Door.active = true;
        }
    }

    onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (otherCollider.group == Constant.Group.PLAYER) {
            this.Door.active = false;
            this.Tips.active = false;
        }
    }
}


